package com.moyu.myadmin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.moyu.myadmin.dao.entity.EmpLeaveEntity;
import com.moyu.myadmin.dao.mapper.EmpLeaveMapper;
import com.moyu.myadmin.model.convert.EmpLeaveConvert;
import com.moyu.myadmin.model.dto.EmpLeaveDTO;
import com.moyu.myadmin.model.vo.EmpLeaveVO;
import com.moyu.myadmin.service.EmpLeaveService;
import com.moyu.myadmin.utils.PageConvert;
import com.moyu.myadmin.utils.ProcInstKey;
import com.moyu.myadmin.utils.QueryData;
import lombok.extern.log4j.Log4j2;
import org.camunda.bpm.engine.RuntimeService;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Log4j2
@Service
public class EmpLeaveServiceImpl extends ServiceImpl<EmpLeaveMapper, EmpLeaveEntity> implements EmpLeaveService {

    private final RuntimeService runtimeService;

    public EmpLeaveServiceImpl(RuntimeService runtimeService) {
        this.runtimeService = runtimeService;
    }

    @Override
    public Page<EmpLeaveVO> queryListPage(QueryData<EmpLeaveDTO> queryData) {
        Page<EmpLeaveEntity> page = new Page<>(queryData.getPageNum(), queryData.getPageSize());
        page = baseMapper.queryListPage(page, queryData.getData());
        List<EmpLeaveVO> voList = EmpLeaveConvert.INSTANCE.toVoList(page.getRecords());
        return PageConvert.convert(page, voList);
    }

    @Override
    public boolean save(EmpLeaveDTO dto) {
        EmpLeaveEntity entity = EmpLeaveConvert.INSTANCE.dtoToEntity(dto);
        return this.saveOrUpdate(entity);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean startProcess(EmpLeaveDTO dto) {
        if (Objects.isNull(dto.getLeaveId())) {
            dto.setLeaveId(IdWorker.getIdStr());
        }
        Map<String,Object> params = new HashMap<>();
        params.put("employee", "admin");
        ProcessInstance instance = runtimeService.startProcessInstanceByKey(ProcInstKey.LOAN_APPROVAL, dto.getLeaveId(), params);
        dto.setProcInstId(instance.getProcessInstanceId());
        log.info("流程实例ID：{}，流程定义ID：{}", instance.getProcessInstanceId(), instance.getProcessDefinitionId());
        return this.save(dto);
    }
}